﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace MingYuanYun.Configuration
{
    public static class ConfigurationBuilderExtensions
    {
        public static IConfigurationBuilder AddDefaultJsonFile(this IConfigurationBuilder builder)
        {
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            return builder;
        }

        public static IConfigurationBuilder AddEnvironmentJsonFile(
            this IConfigurationBuilder builder,
            IEnumerable<string> args,
            string environmentName = HostingEnvironment.DefaultEnvironmentName)
        {
            var environment = HostingEnvironment.GetCommandLineVariable(args, environmentName);

            if (!string.IsNullOrEmpty(environment))
            {
                builder.AddJsonFile(environment);
            }
            else
            {
                builder.AddEnvironmentJsonFile(environmentName);
            }

            return builder;
        }

        public static IConfigurationBuilder AddEnvironmentJsonFile(
            this IConfigurationBuilder builder,
            string environmentName = HostingEnvironment.DefaultEnvironmentName)
        {
            var environment = HostingEnvironment.GetEnvironmentVariable(environmentName);

            if (!string.IsNullOrEmpty(environment))
            {
                builder.AddJsonFile(environment);
            }

            return builder;
        }

        public static IConfigurationBuilder AddEmbeddedJsonFile(this IConfigurationBuilder builder, string path)
        {
            var embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());

            builder.AddJsonFile(embeddedProvider, path, optional: true, reloadOnChange: true);

            return builder;
        }

        public static IConfigurationBuilder AddPhysicalJsonFile(
            this IConfigurationBuilder builder,
            string path,
            string folder = null)
        {
            var directory = Path.GetDirectoryName(path);

            if (string.IsNullOrWhiteSpace(directory))
                directory = Directory.GetCurrentDirectory();

            if (!string.IsNullOrWhiteSpace(folder))
                directory = Path.Combine(directory, folder);

            var provider = new PhysicalFileProvider(directory);

            builder.AddJsonFile(provider, path, optional: true, reloadOnChange: true);

            return builder;
        }

        private static void AddJsonFile(this IConfigurationBuilder builder, string environment)
        {
            builder.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true);
        }
    }
}
